﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using WHW_NetUtility;

namespace MainFrame
{
   public  class UploadInterface
    {
        /// <summary>
        /// 设备运行状态上报
        /// </summary>
        /// <param name="status"></param>
        /// <returns></returns>
        public static ResponEntity upload_DevStatusHead(e_Status status, int DeviceAllDUT, int DeviceNGDUT, double CT)
        {
            try
            {
                var req = new
            {
                DevCode = GlobalVar.userConfig.UploadInfo.DevCode,
                Code = (int)status,
                //生产总数
                Allyield = DeviceAllDUT,
                //生产NG总数
                NGyield = DeviceNGDUT,
                //生产NG总数
                UPH = CT,
                HandleTime = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")
            };
           var res= Uploadweb(GlobalVar.userConfig.UploadInfo.url_DevStatusHead, JsonConvert.SerializeObject(req));
            if (string.IsNullOrEmpty(res))
                return null;
            else
                return JsonConvert.DeserializeObject<ResponEntity>(res);
            }
            catch (Exception ex)
            {
                displalyInfo.displayErrorMain(ex.Message);
                return null;
            }
        }
        /// <summary>
        /// 报警信息上传 
        /// </summary>
        /// <param name="alarm"></param>
        /// <returns></returns>
        public static ResponEntity upload_AlarmUpload(string alarm)
        {
            try
            {
                var req = new
                {
                    DevCode = GlobalVar.userConfig.UploadInfo.DevCode,
                    AlarmData = new
                    {
                        AlarmContent = alarm,
                        AlarmTime = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")
                    }
                };
                var res = Uploadweb(GlobalVar.userConfig.UploadInfo.url_AlarmUpload, JsonConvert.SerializeObject(req));
                if (string.IsNullOrEmpty(res))
                    return null;
                else
                    return JsonConvert.DeserializeObject<ResponEntity>(res);
            }catch(Exception ex)
            {
                displalyInfo.displayErrorMain(ex.Message);
                return null;
            }
        }
        /// <summary>
        /// 进站数据上传
        /// </summary>
        /// <param name="ClampID"></param>
        /// <returns></returns>
        public static ResponEntity upload_CheckUpload(string ClampID)
        {
            try
            {
                var req = new
            {
                DevCode = GlobalVar.userConfig.UploadInfo.DevCode,
                ClampID= ClampID
            };
            var res = Uploadweb(GlobalVar.userConfig.UploadInfo.url_CheckUpload, JsonConvert.SerializeObject(req));
            if (string.IsNullOrEmpty(res))
                return null;
            else
                return JsonConvert.DeserializeObject<ResponEntity>(res);
            }
            catch (Exception ex)
            {
                displalyInfo.displayErrorMain(ex.Message);
                return null;
            }
        }
        /// <summary>
        /// 生产数据上传
        /// </summary>
        /// <param name="Info"></param>
        /// <returns></returns>
        public static ResponEntity upload_DataUpload(ProductInfo Info)
        {
            try
            {
                var req = new
            {
                DevCode = GlobalVar.userConfig.UploadInfo.DevCode,
                ProduceData = new
                {
                    ClampID = Info.ProId,
                    Slot = Info.ProNo,
                    StartTime = Info.LaserTime == null ? "2000/01/01 00:00:00" : Info.LaserTime?.ToString("yyyy/MM/dd HH:mm:ss"),
                    EndTime = Info.LabelTime == null ? "2000/01/01 00:00:00" : Info.LaserTime?.ToString("yyyy/MM/dd HH:mm:ss"),
                    Result = Info.Result.Contains("OK") ? "PASS" : "NG",
                    IsProcessAlarm=Info.IsProcessAlarm,
                    AlarmTime = Info.AlarmTime?.ToString("yyyy/MM/dd HH:mm:ss"),
                }
            };
            var res = Uploadweb(GlobalVar.userConfig.UploadInfo.url_DataUpload, JsonConvert.SerializeObject(req));
            if (string.IsNullOrEmpty(res))
                return null;
            else
                return JsonConvert.DeserializeObject<ResponEntity>(res);
            }
            catch (Exception ex)
            {
                displalyInfo.displayErrorMain(ex.Message);
                return null;
            }
        }
        /// <summary>
        /// 获取总控软件中的产品信息 
        /// </summary>
        /// <returns></returns>
        public static ResponEntity upload_GetModelInfo()
        {
            try
            {
                var req = new
                {
                    DevCode = GlobalVar.userConfig.UploadInfo.DevCode,
                };
                var res = Uploadweb(GlobalVar.userConfig.UploadInfo.url_GetModelInfo, JsonConvert.SerializeObject(req), "POST");
                if (string.IsNullOrEmpty(res))
                    return null;
                else
                    return JsonConvert.DeserializeObject<ResponEntity>(res);
            }
            catch (Exception ex)
            {
                displalyInfo.displayErrorMain(ex.Message);
                return null;
            }
        }
        /// <summary>
        /// 获取总控软件系统时间
        /// </summary>
        /// <returns></returns>
        public static bool upload_GetDate()
        {

            var req = new
            {
                DevCode = GlobalVar.userConfig.UploadInfo.DevCode,
            };
            try
            {
                var res = Uploadweb(GlobalVar.userConfig.UploadInfo.url_GetModelInfo, JsonConvert.SerializeObject(req),"GET");
                if (string.IsNullOrEmpty(res))
                    return false;
                else
                {
                    var dres=JsonConvert.DeserializeObject<ResponEntity>(res);
                    if (dres.DateTime != null)
                    {
                       var newTime= Convert.ToDateTime(dres.DateTime);
                        return Win32API.SetDatetime(newTime);
                    }else
                    {
                        return false;
                    }
                }
            }catch(Exception ex)
            {
                return false;
            }
         
        }
        ///设备启动 
        ///设备暂停
        ///设备复位
        ///设备停止
        ///设备结束作业
        ///设备急停
        ///取出工装
        ///更换产品配方 
        ///更换工装
        public static object lockObj = new object();
        public static string Uploadweb(string url,string jsonstr,string Method = "POST")
        {
            try
            {
                if (!GlobalVar.IsMesTCPOK)
                {
                    Log4Helper.WriteLog("MES信息", "tcp没连接上  不进行上传操作");
                    return "";
                }
                lock (lockObj)
                {
                    HttpWebRequest request = HttpWebRequest.Create(url) as HttpWebRequest;
                    request.Method = Method;
                    request.ContentType = "application/json";
                    request.Timeout = 5000;
                    Log4Helper.WriteLog("信息上传", url + ":" + jsonstr);
                    byte[] data = Encoding.UTF8.GetBytes(jsonstr);
                    Stream newStream = request.GetRequestStream();
                    newStream.Write(data, 0, data.Length);
                    newStream.Close();
                    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                    Stream stream = response.GetResponseStream();
                    StreamReader reader = new StreamReader(stream, Encoding.UTF8);
                    var content = reader.ReadToEnd();
                    reader.Close();
                    response.Close();
                    Log4Helper.WriteLog("信息上传", url + ":" + content);
                    return content;
                }
            }
            catch (Exception ex)
            {
                displalyInfo.displayErrorMain ("upload_url_package" + ex.Message);
                return null;
            }
        }
    }
    public class ResponEntity
    {
        public string Code { get; set; }
        public string Msg { get; set; }
        public DateTime? DateTime { get; set; }
        public List<ModelInfo> ModelInfoList { get; set; }
    }
    public class ModelInfo
    {
        public string Model { get; set; }
        public List<ModelVer> ModelVerInfoList { get; set; }
    }
    public class ModelVer
    {
        public string Ver{ get; set; }
        public string Config { get; set; }
    }
 
    public enum e_Status
    {
        
        正常生产中=1,
        正常待机中=2,
        故障暂停或停止中=3,
        暂停中=4,
        停止中=5,
        设备未复位=6,
        设备复位中 =7,
        设备复位完成 = 8,
        设备急停中=9,
        未知 = 100
    }
    [Serializable]
    public class UrlInfo
    {
        public string url_DeviceName { get; set; }
        public string url_DevStatusHead { get; set; }
        public string url_AlarmUpload { get; set; }
        public string url_CheckUpload { get; set; }
        public string url_DataUpload { get; set; }
        public string url_GetModelInfo { get; set; }
        public string url_GetDate { get; set; }
        public string DevCode { get; set; }
        public bool IsUploadUrl { get; set; }
        public bool IsUploadTcp { get; set; }
    }
    public class Win32API
    {
        [DllImport("Kernel32.dll")]
        public static extern bool SetLocalTime(ref SYSTEMTIME Time);
        [DllImport("Kernel32.dll")]
        public static extern void GetLocalTime(ref SYSTEMTIME Time);
        public static bool SetDatetime(DateTime t)
        {

            //转换System.DateTime到SYSTEMTIME
            SYSTEMTIME st = new SYSTEMTIME();
            st.FromDateTime(t);
            //调用Win32 API设置系统时间(WIN10要管理员才生效)
            bool isOk=Win32API.SetLocalTime(ref st);
            return isOk;
        }
    }
    public struct SYSTEMTIME
    {
        public ushort wYear;
        public ushort wMonth;
        public ushort wDayOfWeek;
        public ushort wDay;
        public ushort wHour;
        public ushort wMinute;
        public ushort wSecond;
        public ushort wMilliseconds;

        /// <summary>
        /// 从System.DateTime转换。
        /// </summary>
        /// <param name="time">System.DateTime类型的时间。</param>
        public void FromDateTime(DateTime time)
        {
            wYear = (ushort)time.Year;
            wMonth = (ushort)time.Month;
            wDayOfWeek = (ushort)time.DayOfWeek;
            wDay = (ushort)time.Day;
            wHour = (ushort)time.Hour;
            wMinute = (ushort)time.Minute;
            wSecond = (ushort)time.Second;
            wMilliseconds = (ushort)time.Millisecond;
        }
        /// <summary>
        /// 转换为System.DateTime类型。
        /// </summary>
        /// <returns></returns>
        public DateTime ToDateTime()
        {
            return new DateTime(wYear, wMonth, wDay, wHour, wMinute, wSecond, wMilliseconds);
        }
        /// <summary>
        /// 静态方法。转换为System.DateTime类型。
        /// </summary>
        /// <param name="time">SYSTEMTIME类型的时间。</param>
        /// <returns></returns>
        public static DateTime ToDateTime(SYSTEMTIME time)
        {
            return time.ToDateTime();
        }
    }
}
